<!DOCTYPE html>
<html lang="zh">
<head>
    <include file="index/index_style" title="PinPaper"/>
</head>
<body class="navbar-fixed">

<!-- header -->
<include file="index/header" sub_news="active" search_action=""/>
<!-- / header -->

<section id="content" class="m-t-small">
    <section class="main padder">
        <div class="row">
            <!--内容主体 start-->

            <div class="col-lg-12">
                <div class="row">
                    <ul class="grid effect-2" id="grid">
                    </ul>
                    <div id="loader">
                        <div id="loaderCircle"></div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</section>


<!-- footer -->
<include file="index/footer"/>
<!-- / footer -->

<script src="__PUBLIC__/js/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="__PUBLIC__/js/bootstrap.js"></script>
<!-- parsley -->
<script src="__PUBLIC__/js/parsley/parsley.min.js"></script>
<!-- Imagesloaded -->
<script src="__PUBLIC__/plugin/imagesloaded.pkgd.min.js"></script>
<!-- Classie -->
<script src="__PUBLIC__/plugin/classie.js"></script>
<!-- Wookmark -->
<script src="__PUBLIC__/plugin/wookmark.min.js"></script>
<!-- Layer -->
<script src="__PUBLIC__/js/layer/layer.js"></script>

<!-- app -->
<script src="__PUBLIC__/js/app.js"></script>
<script src="__PUBLIC__/js/app.plugin.js"></script>
<script src="__PUBLIC__/js/app.data.js"></script>

<!-- Page Script -->
<script>

    //登陆弹出层
    var sign_in_layer_conf = {
        id:'sign_in_layer',
        type: 1,
        closeBtn: 0,
        scrollbar: 0,
        move: false,
        shadeClose: false,
        title: false,
        shade: [0.65, '#000'],
        content: "<section class=\"panel\" style='margin-bottom:0px'>" +
        "<header class=\"panel-heading text-center\"><h4 class='inline text-muted text-center'>登陆PinPaper</h4></header>" +
        "<form class=\"padder\" id='signIn_form' data-validate=\"parsley\">" +
        "<div class=\"block\"><label class=\"control-label text-muted\">邮箱</label>" +
        "<input type=\"email\" name='email' class=\"form-control parsley\" id='signInEmail' placeholder=\"test@example.com\" data-trigger='focusout' data-type='email' data-required='true'></div>" +
        "<div class=\"block\"><label class=\"control-label text-muted\">密码</label>" +
        "<input type=\"password\" name='password' class=\"form-control parsley\" placeholder=\"Password\" data-error-message='请输入密码' data-required='true'></div>" +
        "<div class=\"alert alert-warning message-alert-box\" style=\"display: none\">" +
        "<i class=\"icon-bell-alt\"></i><strong><span class=\"message-alert\"></span></strong>" +
        "</div><div class=\"alert alert-success message-success-box\" style=\"display: none\">" +
        "<i class=\"icon-ok-sign icon-large\"></i><strong><span class=\"message-success\"></span></strong></div>" +
        "<div class=\"line line-dashed\"></div>" +
        "<p class=\"text-muted text-center\"><small>没有账号? <a href='javascript:void(0);' id='signUp'> 请注册</a></small></p>" +
        "<a class=\"btn btn-white btn-block\" id='signInSubmit' href=\"javascript:void(0);\">登陆</a></form></section>"
    };

    //注册弹出层
    var sign_up_layer_conf = {
        id:'sign_up_layer',
        type: 1,
        closeBtn: 0,
        scrollbar: 0,
        move: false,
        shadeClose: false,
        title: false,
        shade: [0.65, '#000'],
        content: "<section class=\"panel\" style='margin-bottom:0px'>" +
        "<header class=\"panel-heading text-center\"><h4 class='inline text-muted text-center'>注册PinPaper</h4></header>" +
        "<form class=\"padder\" id='sign_form' data-validate=\"parsley\">" +
        "<div class=\"block\">" +
        "<label class=\"control-label text-muted\">昵称</label>" +
        "<input type=\"text\" name='username' class=\"form-control parsley\" placeholder=\"Nickname\" data-trigger='keyup' data-maxlength=\"15\" data-required=\"true\">" +
        "</div>" +
        "<div class=\"block\"><label class=\"control-label text-muted\">邮箱</label>" +
        "<input type=\"email\" name='email' class=\"form-control parsley\" id='signUpEmail' placeholder=\"test@example.com\" data-remote=\"{:U('/Home/User/testMail')}\" data-remote-method='POST' data-trigger='focusout' data-type='email' data-required='true'></div>" +
        "<div class=\"block\"><label class=\"control-label text-muted\">密码</label>" +
        "<input type=\"password\" name='password' class=\"form-control parsley\" placeholder=\"Password\" data-rangelength='[6,15]' data-trigger='keyup' data-error-message='密码长度为6-15个字符' data-required='true' id=\"inputPassword\"></div>" +
        "<div class=\"alert alert-warning message-alert-box\" style=\"display: none\">" +
        "<i class=\"icon-bell-alt\"></i><strong><span class=\"message-alert\"></span></strong>" +
        "</div><div class=\"alert alert-success message-success-box\" style=\"display: none\">" +
        "<i class=\"icon-ok-sign icon-large\"></i><strong><span class=\"message-success\"></span></strong></div>" +
        "<div class=\"line line-dashed\"></div>" +
        "<p class=\"text-muted text-center\"><small>已有账号? <a href='javascript:void(0);' id='signIn'> 请登陆</a></small></p><a class=\"btn btn-white btn-block\" id='signSubmit' href=\"javascript:void(0);\">开始</a></form></section>"
    };

    //订阅弹出层
    var subscribe_layer_conf = {
        id:'subscribe_layer',
        type: 2,
        closeBtn: 0,
        scrollbar: 0,
        move: false,
        shadeClose: false,
        title: false,
        area: ['400px','400px'],
        shade: [0.65, '#000'],
        loading:3,
        content: "{:U('/Home/Index/subscribeIframe')}"
    };


    (function ($) {

        $.extend({
            myDate: {
                /**
                 * 时间戳转换日期
                 * @param <int> unixTime    待时间戳(秒)
                 * @param <bool> isFull    返回完整时间(Y-m-d 或者 Y-m-d H:i:s)
                 * @param <int>  timeZone   时区
                 */
                UnixToDate: function(unixTime, isFull, timeZone) {
                    if (typeof (timeZone) == 'number')
                    {
                        unixTime = parseInt(unixTime) + parseInt(timeZone) * 60 * 60;
                    }
                    var time = new Date(unixTime * 1000);
                    var ymdhis = "";
                    ymdhis += (time.getUTCMonth()+1) + "/";
                    ymdhis += time.getUTCDate() + "/";
                    ymdhis += time.getUTCFullYear();
                    if (isFull === true)
                    {
                        ymdhis += " " + time.getUTCHours() + ":";
                        ymdhis += time.getUTCMinutes() + ":";
                        ymdhis += time.getUTCSeconds();
                    }
                    return ymdhis;
                }
            },
            myParam: {
                GetUrlParam: function (name) {
                    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                    var r = window.location.search.substr(1).match(reg);
                    if (r != null) return decodeURI(r[2]);
                    return null;
                }
            }
        });


        //检测登陆
        var islogin = GetCookieValue('islogin');
        if(!islogin) {
            layer.closeAll();
            layer.open(sign_in_layer_conf);
        }


        //初始化瀑布流插件
        var wookmark = undefined,
                page = 1,
                isLoading = false,
                apiURL = "{:U('/news/waterfall')}",
                lastRequestTimestamp = 0,
                fadeInDelay = 1500,
                container = '#grid',
                $container = $(container),
                $loaderCircle = $('#loaderCircle'),
                $window = $(window),
                $document = $(document);


        //滚轮滑到底部时向服务器请求新的数据
        function onScroll(event) {
            // Only check when we're not still waiting for data.
            if (!isLoading) {
                // 滚轮距离内容底部只有100px的时候触发请求
                var closeToBottom = ($window.scrollTop() + $window.height() > $document.height() - 100);
                if (closeToBottom) {
                    // 请求间隔至少1s
                    var currentTime = new Date().getTime();
                    if (lastRequestTimestamp < currentTime - 1000) {
                        lastRequestTimestamp = currentTime;
                        loadData();
                    }
                }
            }
        }


        //刷新布局
        function applyLayout($newImages) {
            $container.append($newImages);

            imagesLoaded(container, function () {
                // Destroy the old handler
                if (wookmark === undefined) {
                    wookmark = new Wookmark(container, {
                        offset: 2, // Optional, the distance between grid items
                        itemWidth: '25%',
                        flexibleWidth: '33%'
                    });
                } else {
                    wookmark.initItems();
                    wookmark.layout(true);
                }

//              设置动画 moveup
                $newImages.each(function () {
                    var $self = $(this);
                    window.setTimeout(function () {
                        $self.addClass("moveup");
                    }, Math.random() * fadeInDelay);
                });
            });
        }


        //从服务器加载数据
        function loadData() {
            isLoading = true;
            $loaderCircle.show();
            var keyword = $.myParam.GetUrlParam('keyword');

            $.ajax({
                url: apiURL,
                dataType: 'json', // 不同域使用jsonp方式
                data: {page: page, type: 'subscribe', keyword: keyword}, // Page parameter to make sure we load new data
                success: onLoadData
            });
        }


        //处理服务器数据,更新页面布局
        function onLoadData(response) {
            isLoading = false;
            $loaderCircle.hide();

            // Increment page index for future calls.
            page++;

            // 构造新闻元素代码
            var html = '',
                    data = response.data,
                    i = 0, length = data.length, news, opacity,
                    $newImages;

            for (; i < length; i++) {
                news = data[i];
                html += '<li>';
                html += '<figure>';
                html += '<figcaption>';
                html += '<div><a class="normal" href="/News/'+ news.id + '" target="_blank">';
                html += '<h3>' + news.title + '</h3>';
                html += '<p>' + news.content + '&nbsp;&nbsp;&nbsp;......</p>';
                html += '</div></a>';
                html += '<div class="line line-dashed"></div>';
                html += '<div class="text-muted text-center text-small">';
                html += '<i class="icon-tag" data-tid="'+ news.topic +'"></i>'+ news.name + '&nbsp;';
                html += '<i class="icon-time"></i>'+ $.myDate.UnixToDate(news.pubtime) +'&nbsp;';
                html += '<i class="icon-comments-alt"></i>'+ news.comments +'&nbsp;';
                html += '<span href="" class='+ ((news.islike&&news.islike=='1')?'active':'') + '>';
                html += '<i class="icon-heart-empty text"></i>';
                html += '<i class="icon-heart text-danger text-active"></i>';
                html += '</span>' + news.likes + '</div>';
                html += '</figcaption></figure></li>';
            }

            $newImages = $(html);

            // 如果到达尾页停止请求
            if (response.message == 'No more news') {
                $document.off('scroll', onScroll);
            }

            // 刷新布局
            applyLayout($newImages);
        }

        //捕获滚轮事件
        $document.on('scroll', onScroll);

        //第一次从服务器加载数据
        loadData();

    })(jQuery);


    $("#signIn").die().live("click", function(){
        layer.closeAll();
        layer.open(sign_in_layer_conf);
    });

    $('#signUp').die().live("click", function () {
        layer.closeAll();
        layer.open(sign_up_layer_conf);
    });

    //登陆表单点击事件
    $('#signInSubmit').die().live("click", function () {

        //表单验证
        var checked = $('#signIn_form').parsley('validate');

        if(checked){
            var data = $("#signIn_form").serialize();
            $.ajax({
                'type': 'post',
                'data': data,
                'url': "{:U('/Home/User/signIn')}",
                'dataType': 'json',
                success: function (data) {
                    if (data.code == '1') {
                        $(".message-alert-box").hide();
                        $(".message-success").text(data.message);
                        $(".message-success-box").fadeIn();
                        setTimeout(function(){
                            window.location.href = '/';
                        },800);
                    } else {
                        $(".message-alert").text(data.message);
                        $(".message-alert-box").fadeIn();
                        $(".message-alert-box").fadeOut(2000);
                    }
                },
                error: function (e) {
                    $(".message-alert").text('服务器繁忙');
                    $(".message-alert-box").fadeIn();
                    $(".message-alert-box").fadeOut(3000);
                }
            });
        }
    });

    //注册表单点击事件
    $('#signSubmit').die().live("click", function () {

        //表单验证
        var checked = $('#sign_form').parsley('validate');

        if(checked){
            var data = $("#sign_form").serialize();
            $.ajax({
                'type': 'post',
                'data': data,
                'url': "{:U('/Home/User/signUp')}",
                'dataType': 'json',
                success: function (data) {
                    if (data.code == '1') {
                        $(".message-alert-box").hide();
                        $(".message-success").text("注册成功,激活邮件已发送,请在1小时内激活哦.");
                        $(".message-success-box").fadeIn();
                        layer.closeAll();
                        layer.open(subscribe_layer_conf);
                    } else {
                        $(".message-alert").text(data.message);
                        $(".message-alert-box").fadeIn();
                        $(".message-alert-box").fadeOut(2500);
                    }
                },
                error: function (e) {
                    $(".message-alert").text('服务器繁忙');
                    $(".message-alert-box").fadeIn();
                    $(".message-alert-box").fadeOut(3000);
                }
            });
        }
    });

</script>

</body>
</html>